package cn.edu.ptu.jobfairs.services.impl;

import cn.edu.ptu.jobfairs.basic.bo.Member;
import cn.edu.ptu.jobfairs.basic.bo.Resume;
import cn.edu.ptu.jobfairs.basic.bo.ResumeEvaluate;
import cn.edu.ptu.jobfairs.basic.common.DataResult;
import cn.edu.ptu.jobfairs.basic.common.Result;
import cn.edu.ptu.jobfairs.basic.common.User;
import cn.edu.ptu.jobfairs.basic.enums.AdviseCode;
import cn.edu.ptu.jobfairs.core.SqlHandler;
import cn.edu.ptu.jobfairs.core.utils.SqlBuilder;
import cn.edu.ptu.jobfairs.core.utils.UserUtils;
import cn.edu.ptu.jobfairs.core.utils.ValidUtils;
import cn.edu.ptu.jobfairs.services.ResumeEvaluateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;

import static cn.edu.ptu.jobfairs.basic.common.Errors.INVALID_PARAMS;

/**
 * @author wutingting.226@163.com
 * @date 2020/9/4
 */
@Service
@Transactional
public class ResumeEvaluateServiceImpl implements ResumeEvaluateService {
    @Resource
    private SqlHandler sqlHandler;

    @Override
    public Result addResumeEvaluate(ResumeEvaluate resumeEvaluate) {
        // 添加意见：同一个人对同一份简历不能重复添加意见
        if (ValidUtils.hasBlank(resumeEvaluate, "id", "memberId", "memberRole",
                "createTime", "updateTime")) return Result.fail(INVALID_PARAMS);
        if (!AdviseCode.exists(resumeEvaluate.getAdvise()))
            return Result.fail(INVALID_PARAMS);
        User user = UserUtils.getUser();
        sqlHandler.notExists(SqlBuilder.from("select count(1) from # where # and # limit 1")
                .append(ResumeEvaluate.class)
                .where("memberId", user.getId())
                .where("resumeId", resumeEvaluate.getResumeId()));
        resumeEvaluate.setMemberId(user.getId());
        resumeEvaluate.setMemberRole(user.getTitle() + " " + user.getName());
        long time = System.currentTimeMillis();
        resumeEvaluate.setCreateTime(time);
        resumeEvaluate.setUpdateTime(time);
        Integer id = sqlHandler.create(SqlBuilder.from("insert into # #")
                .append(ResumeEvaluate.class).insert(resumeEvaluate));
        return DataResult.ok(id);
    }

    @Override
    public Result editResumeEvaluate(ResumeEvaluate resumeEvaluate) {
        // 修改意见：判断是否本人?
        if (resumeEvaluate == null || resumeEvaluate.getId() == null)
            return Result.fail(INVALID_PARAMS);
        if (!AdviseCode.exists(resumeEvaluate.getAdvise())) return Result.fail(INVALID_PARAMS);

        resumeEvaluate.setCreateTime(null);
        resumeEvaluate.setUpdateTime(System.currentTimeMillis());
        sqlHandler.updateOne(SqlBuilder.from("update # set # where # limit 1")
                .append(ResumeEvaluate.class).update(resumeEvaluate)
                .where(resumeEvaluate.getId()));
        return Result.OK;
    }
}
